package scatter.captcha.rest.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import scatter.captcha.pojo.CaptchaStore;
import scatter.captcha.pojo.CaptchaType;
import scatter.captcha.pojo.form.CaptchaQueryForm;
import scatter.captcha.pojo.form.CaptchaValidForm;
import scatter.captcha.pojo.vo.CaptchaVo;
import scatter.captcha.rest.service.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * Created by yangwei
 * Created at 2021/1/14 17:53
 */
@Service
public class CaptchaServiceImpl implements ICaptchaService {

    @Autowired
    private List<ICaptchaProvider> iCaptchaProviderList;
    @Autowired
    private ICaptchaStoreService iCaptchaStoreService;
    @Autowired
    private List<ICaptchaValidator>  iCaptchaValidators;

    @Autowired
    private ICaptchaPreventService iCaptchaPreventService;

    @Override
    public CaptchaVo getCaptcha(CaptchaType captchaType, CaptchaQueryForm queryForm,  HttpServletRequest request) throws IOException {
        CaptchaStore captchaStore = null;
        for (ICaptchaProvider iCaptchaProvider : iCaptchaProviderList) {
            if (iCaptchaProvider.support(captchaType)) {
                captchaStore = iCaptchaProvider.getCaptcha(captchaType);
                iCaptchaStoreService.saveCaptcha(queryForm.getPurpose(),captchaStore,request);
                return (CaptchaVo) captchaStore.getCaptchaData();
            }
        }
        return null;
    }

    @Override
    public boolean validateCaptcha(CaptchaType captchaType, CaptchaValidForm validForm,  HttpServletRequest request) {
        boolean r = false;
        for (ICaptchaValidator iCaptchaValidator : iCaptchaValidators) {
            if (iCaptchaValidator.support(captchaType)) {
                r =  iCaptchaValidator.validate(validForm, iCaptchaStoreService.getCaptcha(validForm.getPurpose(),request));
                break;
            }
        }
        // 验证完成，不论成功还是失败，清除存储的验证码信息，保证不能重复验证
        iCaptchaStoreService.clearCaptcha(validForm.getPurpose(),request);
        // 验证完成，设置阻止状态,这里只负责解除阻止（开锁）
        if (r) {
            iCaptchaPreventService.setShouldValidate(validForm.getPurpose(),!r,request);
        }
        return r;
    }
}
